
from . import article_bp
from formodle import PostArticle,Comments
from flask import redirect, render_template,request,g,abort,flash,url_for
from decoraters import isloginin,isrgroup
from models import Articleq, Userinfo,Groupq,Commentsq
from exts import db
from toolfunc import flash_form_error



@article_bp.route("/post_<int:foid>",methods=["GET","POST"])
@isloginin
def postarticle(foid):
    form=PostArticle()
    if request.method=="GET":
        return render_template("postarticle.html",form=form)
    if request.method=="POST":
        if form.validate_on_submit() is False:
            flash_form_error(form)
            return redirect(url_for("article.postarticle",foid=foid))
        title=request.form.get("title")
        context=request.form.get("context")
        coverimg=request.form.get("coverimg")
        if len(coverimg)>2048:
            flash("URL超过最大长度（2048）")
            return redirect(url_for("article.postarticle",foid=foid))
        if title is not None and context is not None and foid is not None:
            user=Userinfo.query.filter(Userinfo.u_name==g.username).first()
            uid=user.u_id
            user.exp_up(8)
            if coverimg=="":
                coverimg="0"
            newobj=Articleq(u_id=uid,a_title=title,a_context=context,a_vnum=0,a_rnum=0,a_img=coverimg,fo_id=foid)
            db.session.add(newobj)
            db.session.commit()
            flash("发布成功")
            return redirect(url_for("article.articlelist",foid=foid))
        else:
            flash("发布失败")
            return redirect(url_for("article.articlelist",foid=foid))
    else:
        return "???"



@article_bp.route("/No_<int:aid>",methods=["POST",'GET'])
@isloginin
def viewarticle(aid):
    form=Comments()
    if request.method=='GET':
        aimart=Articleq.query.filter(Articleq.a_id==aid).first()
        author=Userinfo.query.filter(Userinfo.u_id==aimart.u_id).first()
        agroup=Groupq.query.filter(Groupq.g_id==author.g_id).first()
        
        if aimart==None:
            abort(404)
        todict=request.args.to_dict()
        if todict.get('page') is None:
            UGC=db.session.query(Userinfo,Groupq,Commentsq).filter(Userinfo.g_id==Groupq.g_id).filter(Commentsq.u_id==Userinfo.u_id).filter(Commentsq.a_id==aid).limit(20)
            aimart.a_vnum+=1
            db.session.commit()
            return render_template("article.html",article=aimart,author=author,agroup=agroup,form=form,UGC=UGC,nuid=g.uid,page=1)
        else:

            page=int(todict.get('page'))
            UGC=db.session.query(Userinfo,Groupq,Commentsq).filter(Userinfo.g_id==Groupq.g_id).filter(Commentsq.u_id==Userinfo.u_id).filter(Commentsq.a_id==aid).limit(20).offset(20*(page-1))
            return render_template("article.html",article=aimart,author=author,agroup=agroup,form=form,UGC=UGC,nuid=g.uid,page=page)
    if request.method=='POST':
        if  form.validate_on_submit() is not True:
            flash_form_error(form=form)
            return redirect(url_for("article.viewarticle",aid=aid))

        newobj=Commentsq(a_id=aid,u_id=g.uid,c_content=request.form.get('context'))
        aimart=Articleq.query.filter(Articleq.a_id==aid).first()
        aimart.a_rnum+=1
        user=Userinfo.query.filter(Userinfo.u_name==g.username).first()
        user.exp_up(3)
        db.session.add(newobj)
        db.session.commit()
        flash("回复成功")
        return redirect(url_for("article.viewarticle",aid=aid))




@article_bp.route("/list_<int:foid>")
@isloginin
def articlelist(foid=1):
    todict=request.args.to_dict()
    page=todict.get('page')
    if page is None:
        aims=Articleq.query.filter(Articleq.fo_id==foid).limit(20)
    else:
        aims=Articleq.query.filter(Articleq.fo_id==foid).limit(20).offset(20*(int(page)-1))
    return render_template("articlelist.html",aims=aims,foid=foid)


@article_bp.route('/del',methods=["POST"])
@isrgroup(8)
@isloginin
def delaorc():
    dtype=request.form.get('dtype')
    did=int(request.form.get('did'))
    if dtype is 'a' and did is not None:
        comts=Commentsq.query.filter(Commentsq.a_id==did).all()
        for comt in comts:
            db.session.delete(comt)
        arti=Articleq.query.filter(Articleq.a_id==did).first()
        foid=arti.fo_id
        db.session.delete(arti)
        db.session.commit()
        flash("删除成功！")
        return redirect(url_for("article.articlelist",foid=foid))
    if dtype is 'c' and did is not None:
        comt=Commentsq.query.filter(Commentsq.c_id==did).first()
        aid=comt.a_id
        db.session.delete(comt)
        db.session.commit()
        flash("删除成功！")
        return redirect(url_for("article.viewarticle",aid=aid))
    flash("删除失败")
    return redirect(url_for("article.articlelist",foid=1))

@article_bp.route('/edit',methods=['GET','POST'])
@isrgroup(8)
@isloginin
def editarti():
    form=PostArticle()
    if request.method=='GET':
        todict=request.args.to_dict()
        eid=todict.get("eid")
        if todict.get("etype") is "a" :
            arti=Articleq.query.filter(Articleq.a_id==eid).first()
            if arti is None:
                flash("要编辑的文章不存在")
                return redirect(url_for("article.articlelist",foid=1))
            else:
            #return render_template('editarti.html',context=request.form.get("context"),title=request.form.get("title"),form=form)
                return render_template('editarti.html',arti=arti,form=form)
    if request.method=="POST":
        if form.validate_on_submit:
            article=Articleq.query.filter(Articleq.a_id == int(request.form.get("aid"))).first()
            if article is None:
                flash("要编辑的文章不存在！")
            else:
                if form.validate_on_submit() is False:
                    flash_form_error(form)
                    return redirect(url_for("article.viewarticle",aid=request.form.get("aid")))
                title=request.form.get("title")
                context=request.form.get("context")
                coverimg=request.form.get("coverimg")
                if len(coverimg)>2048:
                    flash("URL超过最大长度（2048）")
                    return redirect(url_for("article.viewarticle",aid=request.form.get("aid")))
                if title is not None and context is not None:
                    if coverimg=="":
                        coverimg="0"
                    article.a_title=title
                    article.a_context=context
                    article.a_img=coverimg
                    db.session.commit()
                    flash("编辑成功！")
                    return redirect(url_for("article.viewarticle",aid=request.form.get("aid")))
        flash("输入错误")
        return redirect(url_for("article.viewarticle",aid=request.form.get("aid")))

    



